package com.newsvoice.gcm;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.newsvoice.activity.DashBoardActivity;
import com.newsvoice.activity.ICallbackHandler;
import com.newsvoice.activity.NewsVoiceApplication;
import com.newsvoice.activity.R;
import com.newsvoice.activity.ShowNewsActivity;
import com.newsvoice.activity.WebService;

public class PushNotificationRegister extends DashBoardActivity {

	// This is the project id generated from the Google console when
	// you defined a Google APIs project.
	private static final String PROJECT_ID = "1024314874380";

	// This tag is used in Log.x() calls
	private static final String TAG = "PushNotificationRegister";

	// This string will hold the lengthy registration id that comes
	// from GCMRegistrar.register()
	private String regId = "";

	// These strings are hopefully self-explanatory
	private String registrationStatus = "Chưa kích hoạt";
	private String broadcastMessage = "No broadcast message";

	private ProgressDialog dialog;

	// This intent filter will be set to filter on the string
	// "GCM_RECEIVED_ACTION"
	IntentFilter gcmFilter;
	IntentFilter responseFilter;

	// textviews used to show the status of our app's registration, and the
	// latest
	// broadcast message.
	TextView tvRegStatusResult;
	TextView tvBroadcastMessage;
	private Button registerButton;
	private Button unregisterButton;
	private Button receiveNewsByTagButton;
	private Button receiveNewsByTopicButton;

	// This broadcastreceiver instance will receive messages broadcast
	// with the action "GCM_RECEIVED_ACTION" via the gcmFilter

	// A BroadcastReceiver must override the onReceive() event.
	private BroadcastReceiver gcmReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			broadcastMessage = intent.getExtras().getString("gcm");

			if (broadcastMessage != null) {
				// display our received message
				tvBroadcastMessage.setText(broadcastMessage);
			}
		}
	};

	private BroadcastReceiver receiverResponseFromGCMServer = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent intent) {
			// TODO Auto-generated method stub
			if (dialog.isShowing()) {
				dialog.dismiss();
			}

			boolean result = intent.getBooleanExtra("flag", false);
			if (result) {
				registerButton.setVisibility(Button.INVISIBLE);
				unregisterButton.setVisibility(Button.VISIBLE);
				receiveNewsByTagButton.setVisibility(Button.VISIBLE);
				receiveNewsByTopicButton.setVisibility(Button.VISIBLE);

			} else {
				unregisterButton.setVisibility(Button.INVISIBLE);
				receiveNewsByTagButton.setVisibility(Button.INVISIBLE);
				receiveNewsByTopicButton.setVisibility(Button.INVISIBLE);
			}
		}

	};

	// Reminder that the onCreate() method is not just called when an app is
	// first opened,
	// but, among other occasions, is called when the device changes
	// orientation.
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.push_notification_register_layout);
        setHeader(getString(R.string.PushNotificationRegisterActivityTitle),true, true, false, false);

		loadViews();

		// Create our IntentFilter, which will be used in conjunction with a
		// broadcast receiver.
		gcmFilter = new IntentFilter();
		gcmFilter.addAction("GCM_RECEIVED_ACTION");

		responseFilter = new IntentFilter();
		responseFilter.addAction("responseFromGCMServer");
	}

	// This registerClient() method checks the current device, checks the
	// manifest for the appropriate rights, and then retrieves a registration id
	// from the GCM cloud. If there is no registration id, GCMRegistrar will
	// register this device for the specified project, which will return a
	// registration id.
	public void loadViews() {
		tvRegStatusResult = (TextView) findViewById(R.id.tv_reg_status_result);
		registerButton = (Button) findViewById(R.id.register_gcm_button);
		unregisterButton = (Button) findViewById(R.id.unregister_gcm_button);
		receiveNewsByTagButton = (Button) findViewById(R.id.receive_news_automatically_by_tag_button);
		receiveNewsByTopicButton = (Button) findViewById(R.id.receive_news_automatically_by_topic_button);

		registerButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog = new ProgressDialog(PushNotificationRegister.this);
				dialog.setMessage("Please wait...");
				dialog.show();

				System.out.println("registering..");
				registrationStatus = "Registering...";
				tvRegStatusResult.setText(registrationStatus);
				regId = GCMRegistrar.getRegistrationId(getApplicationContext());
				if (regId.equals("")) {
					// register this device for this project
					GCMRegistrar.register(getApplicationContext(), PROJECT_ID);
					regId = GCMRegistrar
							.getRegistrationId(getApplicationContext());

					registrationStatus = "Registration Acquired";
					tvRegStatusResult.setText(registrationStatus);
				}

			}
		});

		unregisterButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

			}
		});

		receiveNewsByTagButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

			}
		});

		receiveNewsByTopicButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(PushNotificationRegister.this, AutomaticalNewsReceiverByTopic.class);
				startActivity(intent);
			}
		});

		try {
			// Check that the device supports GCM (should be in a try / catch)
			GCMRegistrar.checkDevice(this);

			// Check the manifest to be sure this app has all the required
			// permissions.
			GCMRegistrar.checkManifest(this);

			// Get the existing registration id, if it exists.
			regId = GCMRegistrar.getRegistrationId(this);

			if (regId.equals("")) {
				unregisterButton.setVisibility(Button.INVISIBLE);
				receiveNewsByTagButton.setVisibility(Button.INVISIBLE);
				receiveNewsByTopicButton.setVisibility(Button.INVISIBLE);
			} else {
				registerButton.setVisibility(Button.INVISIBLE);
				registrationStatus = getResources().getString(R.string.registry_status);
			}

		} catch (Exception e) {
			e.printStackTrace();
			registrationStatus = e.getMessage();
			registerButton.setVisibility(Button.INVISIBLE);
			unregisterButton.setVisibility(Button.INVISIBLE);
			receiveNewsByTagButton.setVisibility(Button.INVISIBLE);
			receiveNewsByTopicButton.setVisibility(Button.INVISIBLE);
		}

		Log.d(TAG, registrationStatus);
		tvRegStatusResult.setText(registrationStatus);

		// This is part of our CHEAT. For this demo, you'll need to
		// capture this registration id so it can be used in our demo web
		// service.
		Log.d(TAG, regId);

	}

	// If the user changes the orientation of his phone, the current activity
	// is destroyed, and then re-created. This means that our broadcast message
	// will get wiped out during re-orientation.
	// So, we save the broadcastmessage during an onSaveInstanceState()
	// event, which is called prior to the destruction of the activity.
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {

		super.onSaveInstanceState(savedInstanceState);

		savedInstanceState.putString("BroadcastMessage", broadcastMessage);

	}

	// When an activity is re-created, the os generates an
	// onRestoreInstanceState()
	// event, passing it a bundle that contains any values that you may have put
	// in during onSaveInstanceState()
	// We can use this mechanism to re-display our last broadcast message.

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {

		super.onRestoreInstanceState(savedInstanceState);

		broadcastMessage = savedInstanceState.getString("BroadcastMessage");
		tvBroadcastMessage.setText(broadcastMessage);

	}

	// If our activity is paused, it is important to UN-register any
	// broadcast receivers.
	@Override
	protected void onPause() {

		unregisterReceiver(gcmReceiver);
		unregisterReceiver(receiverResponseFromGCMServer);
		super.onPause();
	}

	// When an activity is resumed, be sure to register any
	// broadcast receivers with the appropriate intent
	@Override
	protected void onResume() {
		registerReceiver(gcmReceiver, gcmFilter);
		registerReceiver(receiverResponseFromGCMServer, responseFilter);
		super.onResume();
	}

	// There are no menus for this demo app. This is just
	// boilerplate code.
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	// NOTE the call to GCMRegistrar.onDestroy()
	@Override
	public void onDestroy() {

//		GCMRegistrar.onDestroy(this);

		super.onDestroy();
	}

}
